package com.zyh.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //创建shiroFilter  负责拦截请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(manager);
        /**
         * shiro内置过滤器，可以实现权限相关拦截
         * 常用过滤器：
         * anon：无需认证（登陆）可以访问
         * authc：必须认证才可以访问
         * user：如果使用rememberMe的功能才可以直接访问
         * perms：该资源必须得到资源权限才可以访问
         * role：该资源必须得到角色权限才可以访问
         */
        Map<String,String> map=new HashMap<String,String>();
        map.put("/signup","anon");
        map.put("/login","anon");
        map.put("/css/*","anon");
        map.put("/**","authc");
        bean.setFilterChainDefinitionMap(map);
        //设置没有权限默认访问的路径
        bean.setLoginUrl("/signup");

        return bean;
    }
    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    //创建自定义Realm
    @Bean
    public Realm getRealm(){
        UserRealm userRealm=new UserRealm();
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5"); //加密方式
        credentialsMatcher.setHashIterations(1024);     //散列次数
        userRealm.setCredentialsMatcher(credentialsMatcher);
        return userRealm;
    }
    //整合thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
